package com.lagou.homework.service.impl;

import com.lagou.homework.service.ValidateCodeService;
import com.lagou.homework.dao.TokenDao;
import com.lagou.homework.dao.UserDao;
import com.lagou.homework.pojo.TokenPojo;
import com.lagou.homework.pojo.User;
import com.lagou.homework.service.UserService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {

    @Reference
    ValidateCodeService validateCodeService;
    @Autowired
    UserDao userDao;
    @Autowired
    TokenDao tokenDao;
    @Autowired
    User user;
    @Autowired
    TokenPojo tokenPojo;

    @Override
    public boolean register(String email, String password, String code) {
        // 调用 验证码是否正确的 微服务
        Integer validate = validateCodeService.validate(email, code);
        if (0==validate){
            // 若正确 插入 用户表 表明注册成功
            User user1 = new User();
            user.setId(0);
            user.setEmail(email);
            user.setPassword(password);
            userDao.save(user);
            return true;
        }else{
            System.out.println("验证码返回值:"+validate);
            return false;
        }
    }

    @Override
    public boolean isRegistered(String email) {
        // 在用户表中 查询 email 是否大于 1
        Long count = userDao.findBySql(email);
        if (count>0){
            return true;
        }else {
            return false;
        }
    }

    @Override
    public String login(String email, String password) {
        // 判断合法性
        Long count = userDao.validateSql(email, password);
        if (count>0){
            // 生成 token 并存入 lagou_token 表
            tokenPojo.setId(0);
            String token = UUID.randomUUID().toString().replaceAll("-","");;
            tokenPojo.setToken(token);
            tokenPojo.setEmail(email);
            tokenDao.save(tokenPojo);
            return token;
        }
        return "用户名或密码错误";
    }

    @Override
    public String info(String token) {
        System.out.println(token);
        String email = tokenDao.findTokenBySql(token);
        return email;
    }
}
